<template>
  <!-- 查询栏 -->
  <div class="query">
    <QueryForm :form="form" v-model="queryData" @handleQuery="handleQuery" />
  </div>
  <!-- 表单栏 -->
  <div class="table">
    <BaseTable
      v-loading="tableLoading"
      :columns="columns"
      :data="dataList"
      :pager="pager"
      @handleCurrentChange="handleCurrentChange"
      @handleAction="handleAction"
    >
      <template v-slot:action>
        <el-button type="primary" @click="handleCreate" v-has="'product-add'">新增</el-button>
      </template>
    </BaseTable>
    <!-- 弹窗 -->
    <el-dialog
      :title="action == 'add' ? '新增' : '编辑'"
      v-model="showModal"
      :before-close="handleClose"
    >
      <el-form
        ref="dialogForm"
        :rules="rules"
        :model="dataForm"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="product_name">
          <el-input
            v-model="dataForm.product_name"
            placeholder="请输入商品名称"
          />
        </el-form-item>
        <el-form-item label="商品描述" prop="desc">
          <el-input v-model="dataForm.desc" placeholder="请输入商品描述" />
        </el-form-item>
        <el-form-item label="原价" prop="original_price">
          <el-input
            v-model="dataForm.original_price"
            placeholder="请输入商品原价"
          />
        </el-form-item>
        <el-form-item label="销售价" prop="sale_price">
          <el-input
            v-model="dataForm.sale_price"
            placeholder="请输入商品销售价"
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="dataForm.stock" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="商品分类" prop="cate_id">
          <el-select
            v-model="dataForm.cate_id"
            class="m-2"
            placeholder="请选择商品分类"
            size="small"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品主图" prop="head_img">
          <UploadImage
            :limit="1"
            v-model="dataForm.head_img"
            @change="validParams('head_img')"
          />
        </el-form-item>
        <el-form-item label="商品轮播图" prop="carousel_img">
          <UploadImage
            :limit="4"
            v-model="dataForm.carousel_img"
            @change="validParams('carousel_img')"
          />
        </el-form-item>
        <el-form-item label="商品详情" prop="detail">
          <editor v-model="dataForm.detail"></editor>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="dataForm.status">
            <el-option :value="0" label="下架"></el-option>
            <el-option :value="1" label="上架"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref, toRaw } from "vue";
import {
  getProductList,
  productAdd,
  productEdit,
  productDel,
  queryAllClassificationList,
  productUpdateStatus,
  productUpdateIsHot,
} from "@/api/product";

import Editor from "@/components/Editor.vue";
import UploadImage from "@/components/UploadImage.vue";
import { ElMessage } from "element-plus";
/****************************************** data ******************************************/

// 参数
const pager = reactive({
  page: 1,
  limit: 10,
  total: 0,
});

// 渲染数据
const dataList = ref(<any>[]);

// 编辑动作：add,edit,delete
const action = ref("");

// 弹窗变量
const showModal = ref(false);

// 表格提交数据
const dataForm = ref(<any>{ status: 0, carousel_img: "" });

// 弹窗ref
const dialogForm = ref(<any>null);

// 所有分类数据
const categoryList = ref(<any>[]);

// 表单loading
const tableLoading = ref(false);

// 初始化用户表单对象
const queryData = ref(<any>{ status: null });

// 生成查询form结构数据
const form = [
  {
    type: "input",
    label: "商品名称",
    model: "product_name",
    placeholder: "请输入商品名称",
  },
  {
    type: "select",
    model: "status",
    label: "状态",
    placeholder: "请选择状态",
    options: [
      { label: "下架", value: 0 },
      { label: "上架", value: 1 },
    ],
  },
];

// 定义动态表格的格式
const columns = reactive([
  {
    label: "商品名称",
    prop: "product_name",
    width: 200,
  },
  {
    type: "img",
    label: "商品主图",
    prop: "head_img",
  },
  {
    label: "商品描述",
    prop: "desc",
    width: 200,
  },
  {
    label: "商品原价",
    prop: "original_price",
  },
  {
    label: "商品销售价",
    prop: "sale_price",
  },
  {
    label: "商品库存",
    prop: "stock",
  },
  {
    label: "商品分类",
    prop: "cate_name",
  },
  {
    type: "tag",
    label: "上下架状态",
    prop: "status",
    formatter: (row: any, column: any, value: number) => {
      return {
        0: "下架",
        1: "上架",
      }[value];
    },
    dict: { 
      0: "danger", 
      1: "success", 
    },
  },
  {
    type: "switch",
    label: "热门推荐",
    prop: "is_hot",
    checked: 1,
  },
  {
    type: "switch",
    label: "上下架",
    prop: "status",
    checked: 1,
  },
  {
    label: "创建时间",
    prop: "created_time",
    width: 180,
  },
  {
    label: "更新时间",
    prop: "updated_time",
    width: 180,
  },
  {
    type: "action",
    label: "操作",
    width: 140,
    list: [{ text: "编辑", type: "text", has: "product-edit" }, { text: "删除",confirm: true, has: "product-del"  }],
  },
]);

// 弹窗校验规则
const rules = reactive({
  product_name: [
    {
      required: true,
      message: "请输入商品名称",
      trigger: "blur",
    },
  ],
  desc: [
    {
      required: true,
      message: "请输入商品描述",
      trigger: "blur",
    },
  ],
  original_price: [
    {
      required: true,
      message: "请输入商品原价",
      trigger: "blur",
    },
  ],
  sale_price: [
    {
      required: true,
      message: "请输入商品销售价",
      trigger: "blur",
    },
  ],
  stock: [
    {
      required: true,
      message: "请输入商品库存",
      trigger: "blur",
    },
  ],
  cate_id: [
    {
      required: true,
      message: "请选择商品分类",
      trigger: "change",
    },
  ],
  head_img: [
    {
      required: true,
      message: "请上传主图",
      trigger: "change",
    },
  ],
  carousel_img: [
    {
      required: true,
      message: "请上传轮播图",
      trigger: "blur",
    },
  ],
  detail: [
    {
      required: true,
      message: "请输入商品详情",
      trigger: "blur",
    },
  ],
});

/****************************************** 生命周期函数 ******************************************/

onMounted(async() => {
  setTimeout(()=>{
    getCategoryList();
    handleQuery();
  },500)
});

/****************************************** method ******************************************/

const validParams = (fieldName: String) => {
  if (dialogForm.value) {
    dialogForm.value.validateField(fieldName, () => null);
  }
};

// 查询所有分类
const getCategoryList = async () => {
  let res: any = await queryAllClassificationList({});
  if (res.code === 200) categoryList.value = res.data;
};

// 查询
const handleQuery = async () => {
  tableLoading.value = true;
  let data = (await getProductList({ ...pager, ...queryData.value })).data;
  if (data && data.rows.length > 0 && categoryList.value.length > 0) {
    data.rows.forEach((row: any) => {
      if (categoryList.value.length > 0) {
        for (let index = 0; index < categoryList.value.length; index++) {
          const cate = categoryList.value[index];
          if (cate.id == row.cate_id) {
            row.cate_name = cate.cate_name;
            break;
          }
        }
      }
      if (!row.cate_name) {
        row.cate_name = "未分类";
      }
    });
  }
  dataList.value = data.rows;
  pager.total = data.count;
  tableLoading.value = false;
};

// 分页事件处理
const handleCurrentChange = (current: number) => {
  pager.page = current;
  handleQuery();
};

// 新增
const handleCreate = () => {
  action.value = "add";
  showModal.value = true;
};

// 操作
const handleAction = async ({ text, row }: any) => {
  if (text === "编辑") {
    action.value = "edit";
    showModal.value = true;
    await nextTick();
    Object.assign(dataForm.value, row);
  } else if (text === "删除") {
    await productDel({ id: row.id });
    ElMessage({ message: "删除成功", type: "success" });
    handleQuery();
  } else if (text === "上下架") {
    console.log("上下架");
    let status;
    if (row.status === 1) {
      status = 0;
    } else {
      status = 1;
    }
    await productUpdateStatus({ id: row.id, status });
    ElMessage({ message: "上下架更新成功", type: "success" });
    handleQuery();
  } else if (text === "热门推荐") {
    console.log("热门推荐");
    let is_hot;
    if (row.is_hot === 1) {
      is_hot = 0;
    } else {
      is_hot = 1;
    }
    await productUpdateIsHot({ id: row.id, is_hot });
    ElMessage({ message: "推荐操作成功", type: "success" });
    handleQuery();
  }
};

// 取消
const handleClose = () => {
  showModal.value = false;
  handleReset(dialogForm);
};

// 重置
const handleReset = (form: any) => {
  form.value.resetFields();
};

// 提交
const handleSubmit = () => {
  let res: any;
  dialogForm.value.validate(async (valid: boolean) => {
    if (valid) {
      let params = toRaw(dataForm.value);
      if (action.value === "add") {
        res = await productAdd(params);
      } else if (action.value === "edit") {
        res = await productEdit(params);
      }
      if (res && res.code === 200) {
        showModal.value = false;
        ElMessage({ message: "操作成功", type: "success" });
        handleReset(dialogForm);
        handleQuery();
      }
    }
  });
};
</script>

<style lang="scss" scoped></style>
